package com.yj.oa.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yj.api.OA_API;
import com.yj.common.responses.OAResponse;
import com.yj.common.responses.TerminalResponse;
import com.yj.oa.dto.oa.LoginDto;
import com.yj.oa.dto.system.OABindingDto;
import com.yj.oa.entity.oa.User;
import com.yj.oa.entity.system.OAUserInfo;
import com.yj.oa.entity.system.UserRelationship;
import com.yj.oa.service.OABindingService;
import com.yj.oa.service.OAInfoService;
import com.yj.util.http.RetrofitClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import retrofit2.Call;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Copyright 2017 (C) Yunjian-VC
 * Created on : 2017/12/1
 * Author     : Unbelievable9
 **/
@Api(tags = "易煤可视化-OA绑定")
@Controller
@RequestMapping("/binding")
public class OABindingController {

    private static final Gson gson = new Gson();

    private OA_API oa_api = RetrofitClient.getOARetrofit().create(OA_API.class);

    @Autowired
    private OABindingService oaBindingService;

    @Autowired
    private OAInfoService oaInfoService;

    private String bindUser(LoginDto oaLoginDto) throws IOException {
        String oaBindingJson = gson.toJson(oaLoginDto);

        Call<String> call = oa_api.bindUser(Base64Utils.encodeToString(oaBindingJson.getBytes("UTF-8")));

        return call.execute().body();
    }

    private String getUserInfo(String token) throws IOException {
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("token", token);

        String tokenJson = gson.toJson(requestMap);

        Call<String> call = oa_api.getUserInfo(Base64Utils.encodeToString(tokenJson.getBytes("UTF-8")));

        return call.execute().body();
    }

    @ApiOperation("易煤用户白名单检测")
    @GetMapping("/whitelist-check")
    @ResponseBody
    public TerminalResponse<Objects> whitelistCheck(@ApiParam(value = "易煤用户ID", required = true) @RequestParam("phone") String phone) {
        Boolean inWhitelist = oaBindingService.whiteListCheck(phone);

        if (!inWhitelist) {
            return new TerminalResponse<>(false, "用户不在可视化系统白名单内" , null);
        } else {
            return new TerminalResponse<>(true, "用户在可视化系统白名单内", null);
        }
    }

    @ApiOperation("易煤用户OA绑定检测")
    @GetMapping("/binding-check")
    @ResponseBody
    public TerminalResponse<Map> bindingCheck(@ApiParam(value = "易煤用户ID", required = true) @RequestParam("id") Integer id) {
        OAUserInfo oaUserInfo = oaBindingService.bindingCheck(id);

        if (oaUserInfo == null) {
            return new TerminalResponse<>(false, "易煤用户未绑定OA", null);
        } else {
            String error = oaInfoService.updateRoleInfoForUser(oaUserInfo);

            if (error == null) {
                Map<String, Object> infoMap = oaInfoService.getBindingInfo(oaUserInfo);

                return new TerminalResponse<>(true, "易煤用户已绑定OA", infoMap);
            } else {
                return new TerminalResponse<>(false, error, null);
            }
        }
    }

    @ApiOperation("易煤用户绑定OA系统")
    @PostMapping("/bind")
    @ResponseBody
    public TerminalResponse<Map> bind(@RequestBody OABindingDto oaBindingDto) {
        String oaResponseString;

        try {
            oaResponseString = bindUser(new LoginDto(oaBindingDto.getOa_username(), oaBindingDto.getOa_password()));

            if (!StringUtils.isEmpty(oaResponseString)) {
                Type oaResponseType = new TypeToken<OAResponse<User>>(){}.getType();
                String oaResponseJson = new String(Base64Utils.decode(oaResponseString.getBytes()), "UTF-8");
                Map<String, String> dataMap = new HashMap<>();

                OAResponse<User> oaResponse = gson.fromJson(oaResponseJson, oaResponseType);

                if (oaResponse.getStatus() == 1) {
                    OAUserInfo oaUserInfo = oaBindingService.bindingCheck(oaBindingDto.getYm_user_id());
                    UserRelationship userRelationship = oaBindingService.oaCheck(oaBindingDto.getOa_username());

                    if (oaUserInfo != null) {
                        dataMap.put("bound", "-1");

                        return new TerminalResponse<>(false,"该账号已绑定，如有疑问请联系客服", dataMap);
                    }


                    if (userRelationship != null) {
                        dataMap.put("bound", "-1");

                        return new TerminalResponse<>(false,"OA用户ID为: " + userRelationship.getOa_user_id() + " 已经被绑定，如有疑问请联系客服", dataMap);
                    }

                    oaBindingService.createNewRelationship(oaBindingDto, oaResponse.getData());

                    dataMap.put("token", oaResponse.getData().getToken());
                    dataMap.put("bound", "1");

                    return new TerminalResponse<>(true,"用户绑定成功", dataMap);
                } else {
                    dataMap.put("bound", "0");

                    return new TerminalResponse<>(false, oaResponse.getMessage(), dataMap);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new TerminalResponse<>(false, "用户绑定失败", null);
    }

    @Transactional
    @ApiOperation("获取OA用户角色信息")
    @GetMapping(value = "/oa-user-info")
    @ResponseBody
    public TerminalResponse<Map> oaUserInfo(@RequestHeader String token) {
        String oaResponseString;

        try {
            oaResponseString = getUserInfo(token);

            if (!StringUtils.isEmpty(oaResponseString)) {
                Type oaResponseType = new TypeToken<OAResponse<OAUserInfo>>(){}.getType();
                String oaResponseJson = new String(Base64Utils.decode(oaResponseString.getBytes()), "UTF-8");

                OAResponse<OAUserInfo> oaResponse = gson.fromJson(oaResponseJson, oaResponseType);

                if (oaResponse.getStatus() == 1) {
                    OAUserInfo oaUserInfo = oaResponse.getData();

                    // 更新用户OA信息
                    String error = oaInfoService.updateRoleInfoForUser(oaUserInfo);

                    if (error == null) {
                        oaBindingService.createNewOAUserInfo(oaResponse.getData());

                        Map<String, Object> dataMap = new HashMap<>();
                        dataMap.put("user", oaResponse.getData());
                        dataMap.put("sub", oaInfoService.getSubItemMapByUser(oaUserInfo));

                        return new TerminalResponse<>(true, "获取OA用户角色信息成功", dataMap);
                    } else {
                        return new TerminalResponse<>(false, error, null);
                    }
                } else {
                    return new TerminalResponse<>(false, oaResponse.getMessage(), null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new TerminalResponse<>(false, "获取OA用户角色信息失败", null);
    }
}
